using MediatR;
using RBAC.Domain.SalesManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.ERP.SalesManagement;
using Dapper;
namespace RBAC.Read.Api.Application.Handler.ERP.SalesManagement
{
    public class GetPrintCustomerCommandHandler : IRequestHandler<GetPrintCustomerCommands, APIResult<List<Customer>>>
    {
        private readonly IBaseRepository<Customer> _customerRepo;

        public GetPrintCustomerCommandHandler(IBaseRepository<Customer> customerRepo)
        {
            _customerRepo = customerRepo;
        }

        public Task<APIResult<List<Customer>>> Handle(GetPrintCustomerCommands request, CancellationToken cancellationToken)
        {
            try
            {
                var where = string.Empty;
                var param = new DynamicParameters();

                if (!string.IsNullOrWhiteSpace(request.CustomerName))
                {
                    where += (where == string.Empty ? string.Empty : " AND ") + "CustomerName LIKE @CustomerName";
                    param.Add("@CustomerName", $"%{request.CustomerName}%");
                }

                if (!string.IsNullOrWhiteSpace(request.Phone))
                {
                    where += (where == string.Empty ? string.Empty : " AND ") + "Phone LIKE @Phone";
                    param.Add("@Phone", $"%{request.Phone}%");
                }

                // 不分页，打印场景直接返回完整列表
                var data = _customerRepo.GetAll(where, param) ?? new List<Customer>();

                return Task.FromResult(new APIResult<List<Customer>>
                {
                    Code = APIEnums.Success,
                    Msg = "查询成功",
                    Data = data
                });
            }
            catch (Exception ex)
            {
                return Task.FromResult(new APIResult<List<Customer>>
                {
                    Code = APIEnums.Fail,
                    Msg = "查询失败：" + ex.Message,
                    Data = new List<Customer>()
                });
            }
        }
    }
}
